package com.yuxi.Controller.Impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.google.gson.Gson;
import com.yuxi.Config.ConfigStatic;
import com.yuxi.Config.UserTableStatic;
import com.yuxi.Controller.UtilController;
import com.yuxi.Dao.IExcelDao;
import com.yuxi.Dao.InfoChangeRecordDao;
import com.yuxi.Dao.InformationDao;
import com.yuxi.Dao.InformationPortDao;
import com.yuxi.Dao.OwnWordRecordDao;
import com.yuxi.Dao.OwnwordRecordBorwserDao;
import com.yuxi.Dao.PrisonStructureDao;
import com.yuxi.Dao.TaskDispatchDao;
import com.yuxi.Dao.UserInfoDao;
import com.yuxi.Entity.CommentRecord;
import com.yuxi.Entity.FirstCheckExcel;
import com.yuxi.Entity.Information;
import com.yuxi.Entity.InformationFlow;
import com.yuxi.Entity.InformationPort;
import com.yuxi.Entity.PowerRole;
import com.yuxi.Entity.PrisonStructure;
import com.yuxi.Entity.TaskDispatch;
import com.yuxi.Entity.UserInfo;
import com.yuxi.Entity.UserView;
import com.yuxi.Request.InformationQuery;
import com.yuxi.Request.OwnExport;
import com.yuxi.Request.OwnQuery;
import com.yuxi.Request.Page;
import com.yuxi.Request.UserCustomRequest;
import com.yuxi.Request.UserQuery;
import com.yuxi.Response.FileUpAddress;
import com.yuxi.Response.Msg;
import com.yuxi.Response.Obj;
import com.yuxi.Response.PageQuerySave;
import com.yuxi.Service.InformationFlowService;
import com.yuxi.Service.PrisonService;
import com.yuxi.Service.UserInformationService;
import com.yuxi.Service.UserService;
import com.yuxi.Service.UtilService;
import com.yuxi.Util.ExportExcel;
import com.yuxi.Util.ExportExcelUtil;
import com.yuxi.Util.ExportOwnWord;
import com.yuxi.Util.ExportTaskWord;
import com.yuxi.Util.ExportUserCustomServlet;
import com.yuxi.Util.ExportWordUtil;
import com.yuxi.Util.ExportWordUtilServlet;
import com.yuxi.Util.GsonUtil;
import com.yuxi.Util.IPUtil;
import com.yuxi.Util.ImageUtil;
import com.yuxi.excelEntity.Analysis;
import com.yuxi.excelEntity.ExportRsRj;
import com.yuxi.excelEntity.OwnWordInfo;
import com.yuxi.excelEntity.OwnWordRecord;
import com.yuxi.excelEntity.OwnwordRecordBorwser;
import com.yuxi.excelEntity.RealtimeTasks;
import com.yuxi.excelEntity.TaskContainer;
import com.yuxi.excelEntity.TaskReseachWord;
import com.yuxi.excelEntity.Tasks;
import com.yuxi.excelEntity.UserCustom;
import com.yuxi.view.UserPowerView;

import jdk.nashorn.internal.runtime.regexp.joni.Config;

@Controller
public class UtilControllerImpl implements UtilController {
	@Autowired
	private UserInfoDao userInfoDao;
	@Autowired
	private UserService userService;
	@Autowired
	private InformationPortDao informationPortDao;
	@Autowired
	private IExcelDao excelDao;
	@Autowired
	private UtilService utilService;
	@Autowired
	private PrisonStructureDao prisonStructureDao;
	@Autowired
	private UserInformationService userInformationService;
	@Autowired
	private OwnWordRecordDao ownWordRecordDao;
	@Autowired
	private InfoChangeRecordDao infoChangeRecordDao;
	@Autowired
	private OwnwordRecordBorwserDao  ownwordRecordBorwserDao;
	@Autowired
	private InformationDao informationDao;
	@Autowired
	private InformationFlowService informationFlowService;
	@Autowired
	private PrisonService prisonService;
	
	private Gson gson = new Gson();
	private Logger logger = LoggerFactory.getLogger(UtilControllerImpl.class);

	@Override
	public String userFileUp(@RequestParam("files") MultipartFile[] files, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("开始上传文件。。。");
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		List<String> webPathAddress = new ArrayList<String>();
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求

		if (multipartResolver.isMultipart(request)) {
			for (int i = 0; i < files.length; i++) {
				MultipartFile file = files[i];
				// 记录上传过程起始时的时间，用来计算上传时间
				int pre = (int) System.currentTimeMillis();
				// 取得上传文件
				if (file != null) {
					// 取得当前上传文件的文件名称
					String myFileName = file.getOriginalFilename();
					// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
					if (myFileName.trim() != "") {
						// file.get
						// 重命名上传后的文件名
						Long datelong = System.currentTimeMillis();// 定义一个时间戳
						String dateStr = Long.toString(datelong, 36).toLowerCase()
								+ Integer.toString((int) (Math.random() * 999));
						String webFileName = file.getOriginalFilename();
						String prefix = webFileName.substring(webFileName.lastIndexOf("."));
						String fileName = dateStr + Long.toString(System.currentTimeMillis()) + prefix;
						// 定义上传路径
						String realPath = request.getServletContext().getRealPath("/") + "Upload\\";

						String path = realPath + fileName;

						String ip = request.getRemoteAddr();
						
						System.out.println(path);
						File localFile = new File(path);
						// new MimetypesFileTypeMap().getContentType();
						try {
							File file2 = new File(realPath);
							try {
								if (!file2.exists() && !file2.isDirectory()) {
									file2.mkdir();
								}
							} catch (Exception e) {
								file2.mkdir();
							}
							String typeStr = file.getContentType().substring(0, 5);
							String url = request.getScheme() + "://";
							url += request.getHeader("host");
							if (typeStr.equals("image")) {
								ImageUtil s = new ImageUtil(file.getInputStream(), path);
								s.resizeFix(400, 400);
								webPathAddress.add(url + "/yuxi/Upload/" + fileName);

							} else {
								webPathAddress.add(url + "/yuxi/Upload/" + fileName);
								file.transferTo(localFile);
							}

						} catch (IllegalStateException e) {
							FileUpAddress fileAddress = new FileUpAddress(false, "文件上传失败", null,
									System.currentTimeMillis(), "1001", "文件上传");
							logger.error(fileAddress.toString());
							return gson.toJson(fileAddress);
						} catch (IOException e) {

							FileUpAddress fileAddress = new FileUpAddress(false, "文件上传失败", null,
									System.currentTimeMillis(), "1002", "文件上传");
							logger.error(fileAddress.toString());
							return gson.toJson(fileAddress);
						}
					}
				}

			}
			FileUpAddress fileAddress = new FileUpAddress(true, "文件上传成功", webPathAddress, System.currentTimeMillis(),
					null, "文件上传");
			logger.info(fileAddress.toString());
			return gson.toJson(fileAddress);
		}

		FileUpAddress fileAddress = new FileUpAddress(false, "文件上传失败", null, System.currentTimeMillis(), "1003",
				"文件上传");
		logger.info(fileAddress.toString());
		return gson.toJson(fileAddress);
	}

	@Override
	public void importExcel(int[] idArray, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws IOException {
		String fileName = "初审汇总表";
		ExportExcel<FirstCheckExcel> ex = new ExportExcel<FirstCheckExcel>();
		String[] headers = { "信息内容", "信息分级", "处置措施", "派遣人", "派遣时间", "完成时限", "完成情况", "责任人", "派遣备注" };
		Integer[] headersL={24,16,24,16,16,16,24,12,12,8};
	
		List<FirstCheckExcel> dataset = userInformationService.getInfotmationByIdArray(idArray);
		
		new ExportExcelUtil<FirstCheckExcel>().importExcel(ex, dataset, fileName, headers,headersL, fileName, request, response);
	}

	@Override
	public void imporExcelForAnalysis(int[] idArray, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws IOException {
		String pName=userService.curLoginUserPowerView(session).getMaxStructure().getName();
		String fileName = pName+"大安全信息分析研判表";
		ExportExcel<Analysis> ex = new ExportExcel<Analysis>();
		String[] headers = { "序号", "分口", "渠道", "类型", "信息内容", "信息处置情况", "处置措施", "责任人", "完成时限", "备注" };
		Integer[] headersL={6,8,8,8,28,20,16,12,12,8};
		List<Analysis> dataset = excelDao.outExcelForAnalysis(idArray);
		System.out.println(dataset);
		ExportExcelUtil<Analysis> x=new ExportExcelUtil<Analysis>();
		x.isLand=true;
		x.importExcel(ex, dataset, fileName, headers,headersL, fileName, request, response);
	}

	@Override
	public void imporExcelForRealtimeTasks_prisonArea(int[] idArray, HttpServletRequest request,
			HttpServletResponse response, HttpSession session) throws IOException {
		PrisonStructure p = userService.curLoginUserPowerView(session).getMaxStructure();
		String fileName =  p.getName()+"（监管、生产、政工）大安全工作即时任务派遣单";
		ExportExcel<RealtimeTasks> ex = new ExportExcel<RealtimeTasks>();
		String[] headers = { "序号", "信息内容", "措施", "派遣人", "完成时限", "责任人签字" };
		Integer[] headersL={8,34,34,16,16,16};
		List<RealtimeTasks> dataset = excelDao.outExcelForRealtimeTasks(idArray);
		new ExportExcelUtil<RealtimeTasks>().importExcel(ex, dataset, fileName, headers,headersL,fileName, request, response);
	}

	@Override
	public void imporExcelForRealtimeTasks_prison(int[] idArray, HttpServletRequest request,
			HttpServletResponse response, HttpSession session) throws IOException {
		UserInfo u = userService.getCurLoginUser(session);
		PrisonStructure p = userService.curLoginUserPowerView(session).getMaxStructure();		
		if (!p.getValue().equals("Prison")) {
			imporExcelForRealtimeTasks_prisonArea(idArray, request, response, session);
		} else {
			
			String fileName = p.getName()+"（监管、生产、政工、后勤）大安全工作即时任务派遣单";
			ExportExcel<RealtimeTasks> ex = new ExportExcel<RealtimeTasks>();
			String[] headers = { "序号", "信息内容", "措施", "派遣人", "完成时限", "责任人签字" };
			Integer[] headersL={8,34,34,16,16,16};
			List<RealtimeTasks> dataset = excelDao.outExcelForRealtimeTasks(idArray);
			new ExportExcelUtil<RealtimeTasks>().importExcel(ex, dataset, fileName, headers,headersL, fileName, request,
					response);
		}

	}

	@Override
	public void imporExcelForTasks_prisonArea(int[] idArray, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws IOException {
	
		ExportExcel<Tasks> ex = new ExportExcel<Tasks>();
		String[] headers = { "序号", "信息内容", "措施", "派遣人", "完成时限", "责任人签字" };
		List<Tasks> dataset = excelDao.outExcelForTasks(idArray);
		UserInfo u = userService.getCurLoginUser(session);
		PrisonStructure p = userService.curLoginUserPowerView(session).getMaxStructure();
		String fileName = p.getName()+"（监管、生产、政工）大安全工作任务派遣单";
		Integer[] headersL={8,34,34,16,16,16};
//		List<UserInfo> ulist = userService.getPrisonHeader(p.getId());
//		StringBuilder spb = new StringBuilder("");
//		Iterator<UserInfo> it = ulist.iterator();
//		int index = 0;
//		while (it.hasNext()) {
//			if (index > 0) {
//				spb.append(",");
//			}
//			index++;
//			spb.append(it.next().getUserName());
//
//		}
//		List<UserInfo> ulist1 = userService.getPrisonViceHeader(p.getId());
//		StringBuilder spb1 = new StringBuilder("");
//		Iterator<UserInfo> it1 = ulist1.iterator();
//		index = 0;
//		while (it1.hasNext()) {
//			if (index > 0) {
//				spb.append(",");
//			}
//			index++;
//			spb1.append(it1.next().getUserName());
//		}
//
//		String areaBoss = spb.toString();
//		String areaBoss2 = spb1.toString();

		SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
		String time = format.format(new Date());
		new ExportExcelUtil<Tasks>().importExcel(ex, dataset, fileName, headers, headersL,fileName,
				request, response);
	}

	@Override
	public void imporExcelForTasks_prison(int[] idArray, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws IOException {
		
		ExportExcel<Tasks> ex = new ExportExcel<Tasks>();
		String[] headers = { "序号", "信息内容", "措施", "派遣人", "完成时限", "责任人签字" };
		// {"信息内容", "分级", "处置标准和措施","派遣时间","派遣人","完成时限","完成情况","责任人签字","派遣备注"};
		Integer[] headersL={8,34,34,16,16,16};
		List<Tasks> dataset = excelDao.outExcelForTasks(idArray);
		UserInfo u = userService.getCurLoginUser(session);
		PrisonStructure p = userService.curLoginUserPowerView(session).getMaxStructure();
		String fileName = p.getName()+"（监管、生产、政工、后勤）大安全工作任务派遣单";
//		if (!p.getValue().equals("Prison")) {
//			imporExcelForTasks_prisonArea(idArray, request, response, session);
//		} else {
//			List<UserInfo> ulist = userService.getPrisonHeader(p.getId());
//			StringBuilder spb = new StringBuilder("");
//			Iterator<UserInfo> it = ulist.iterator();
//			int index = 0;
//			while (it.hasNext()) {
//				if (index > 0) {
//					spb.append(",");
//				}
//				index++;
//				spb.append(it.next().getUserName());
//			}
//			List<UserInfo> ulist1 = userService.getPrisonViceHeader(p.getId());
//			StringBuilder spb1 = new StringBuilder("");
//			Iterator<UserInfo> it1 = ulist1.iterator();
//			index = 0;
//			while (it1.hasNext()) {
//				if (index > 0) {
//					spb.append(",");
//				}
//				index++;
//				spb1.append(it1.next().getUserName());
//			}
//			String areaBoss = spb.toString();
//			String areaBoss2 = spb1.toString();
			SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
			String time = format.format(new Date());
//			new ExportExcelUtil<Tasks>().importExcel(ex, dataset, fileName, headers, fileName,
//					"      监区长：" + areaBoss + "             分管领导：" + areaBoss2 + "      时间：" + time + "", request,
//					response);
			new ExportExcelUtil<Tasks>().importExcel(ex, dataset, fileName, headers,headersL, fileName, request,
					response);
		

	}

	@Override
	public void importWord(String time, String address, String people, String context, HttpServletRequest request,
			HttpServletResponse response, HttpSession session) throws IOException {
		List<String> datalist = new ArrayList<String>();
		datalist.add(time);
		datalist.add(address);
		datalist.add(people);
		datalist.add(context);
		new ExportWordUtil().importWord(datalist, request, response);
	}

	@Override
	public void exportPoliceOwn(String startTime,String endTime, HttpSession session, HttpServletRequest request,
			HttpServletResponse response) {
		
		if(startTime.equals("请选择起始时间")||endTime.equals("请选择终止时间")){
			long startTimestamp=System.currentTimeMillis()-60*60*24*7*1000;
			long endTimestamp=System.currentTimeMillis();
			Date start=new Date(startTimestamp);
			Date end=new Date(endTimestamp);
			startTime=new SimpleDateFormat("yyyy/MM/dd").format(start);
			endTime=new SimpleDateFormat("yyyy/MM/dd").format(end);			
		}		
		
		utilService.exportPoliceOwn(startTime,endTime,session, request, response);
	}

	@Override
	public String policeQuery(InformationQuery query, HttpSession session) {
		;
		try {
			List<Information> iList = excelDao.getInforList(query, userService.getCurLoginUser(session).getUserId());
			Obj obj = new Obj(true, "获取民警个人信息成功", iList, System.currentTimeMillis(), null, "民警个人查询信息");
			logger.info("获取民警个人信息成功");
			return gson.toJson(obj);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取民警个人信息失败");
			Obj obj = new Obj(true, "获取民警个人信息失败", null, System.currentTimeMillis(), "1001", "民警个人查询信息");
			return gson.toJson(obj);
		}
	}

	@Override
	public String getCanCheckPrison(HttpSession session) {
		try {
			UserPowerView userPower = userService.curLoginUserPowerView(session);
			PowerRole userRoleP = userPower.getPowerRole();
			PrisonStructure psuct = userPower.getMaxStructure();
			List<PrisonStructure> rs = new ArrayList<PrisonStructure>();
//			if (userRoleP.isPrisonAreaInfoAdd() && userRoleP.isPrisonAreaInfoAdd()) {
//				if (psuct.getValue().equals("Prison")) {
//					rs = prisonStructureDao.getAllPrisonAndAreaStructure();
//				} else {
//					rs = prisonStructureDao.getAllPrisonStructure();
//					//rs.add(psuct);
//					rs.add(0, psuct);
//				}
//			} else {
//				rs.add(psuct);
//			}
			if(psuct.getValue().equals("Prison")){
				if(userRoleP.isPrisonInfoAdd()){
					rs.add(0, psuct);			
				}
				if(userRoleP.isPrisonAreaInfoAdd()){
					rs.addAll(prisonStructureDao.getAllPrisonArea());					
				}
			}else{
				if(userRoleP.isPrisonInfoAdd()){
					rs.addAll(prisonStructureDao.getAllPrisonStructure());		
				}
				if(userRoleP.isPrisonAreaInfoAdd()){
					//rs.addAll(prisonStructureDao.getAllPrisonArea());
					rs.add(0, psuct);
				}
				
			}
			
			Obj obj = new Obj(true, "获取可选择的监区监狱成功", rs, System.currentTimeMillis(), null, "获取可选择的监区监狱");
			return gson.toJson(obj);
		} catch (Exception e) {
			Obj obj = new Obj(false, "获取可选择的监区监狱失败", null, System.currentTimeMillis(), "1001", "获取可选择的监区监狱");
			return gson.toJson(obj);
		}
	}

	@Override
	public String getQueryPoleceTableList(OwnQuery query, Page<OwnWordRecord> p, HttpSession session) {
		Integer pId = userService.curLoginUserPowerView(session).getMaxStructure().getId();
		query.setPrisnoId(pId);
		//ownQueryPage
		PageQuerySave<OwnQuery> pageQuerySave=new PageQuerySave<OwnQuery>(query, p.getCurrentPage());
		PageQuerySave<OwnQuery> pageQuerySaveSeesion=(PageQuerySave<OwnQuery>)session.getAttribute("ownerQueryPage");
		if(pageQuerySaveSeesion!=null&&pageQuerySaveSeesion.isEable()){
			query=pageQuerySaveSeesion.getQuery();
			p.setCurrentPage(pageQuerySaveSeesion.getPageNum());
		}
		UserInfo user=null;
		try{
			if(query.getUserAB()!=null&&!query.getUserAB().isEmpty()){
				user=userInfoDao.getUserListByUserAccountOrName(query.getUserAB()).get(0);	
				query.setUserAB(user.getUserName());
			}
			String str=gson.toJson(ownWordRecordDao.getOwnWordListByQuery(query, p));
			session.setAttribute("ownerQueryPage",pageQuerySave);
			return str;
		}catch(Exception e){
			//e.printStackTrace();
			session.setAttribute("ownerQueryPage",pageQuerySave);
			return gson.toJson(new Page<OwnWordRecord>());	
		}		
	}

	@Override
	public String getCanChangePrison(Integer infoId, HttpSession session) {
		try {
			UserPowerView userPower = userService.curLoginUserPowerView(session);
			PrisonStructure psuct = userPower.getMaxStructure();
			List<PrisonStructure> rs = new ArrayList<PrisonStructure>();
			if (psuct.getValue().equals("Prison")) {
				rs = prisonStructureDao.getAllPrisonAreaStructure();
			} else {
				rs = prisonStructureDao.getAllPrisonStructure();
			}
			Map<String, Object> rsMap = new HashMap<String, Object>();
			rsMap.put("list", rs);
			rsMap.put("souce", infoChangeRecordDao.getNearlyRecordByInfoId(infoId));
			Information infor= informationDao.getInformationById(infoId);
			String inpss=infor.getInformationSourceNames();
			Pattern pattern = Pattern.compile(".*日搜日解.*");
			Matcher matcher = pattern.matcher(inpss);
			boolean b= matcher.matches();
			if(!b){
				Obj obj = new Obj(false, "获取可选择的监区监狱失败", null, System.currentTimeMillis(), "1001", "获取可选择的监区监狱");
				return gson.toJson(obj);
			}
			Obj obj = new Obj(true, "获取可选择的监区监狱成功", rsMap, System.currentTimeMillis(), null, "获取可选择的监区监狱");
			return gson.toJson(obj);
		} catch (Exception e) {
			Obj obj = new Obj(false, "获取可选择的监区监狱失败", null, System.currentTimeMillis(), "1001", "获取可选择的监区监狱");
			return gson.toJson(obj);
		}
	}

	@Override
	public void exportExcelRsRj(String startTime,String endTime, HttpSession session, HttpServletRequest request,
			HttpServletResponse response) {
		UserInfo u= userService.getCurLoginUser(session);
		List<ExportRsRj> dataset = excelDao.getRsRjList(startTime,endTime,u.getUserId());		
		Collections.sort(dataset, new Comparator<ExportRsRj>() {
			public int compare(ExportRsRj o1, ExportRsRj o2) {			
				if (o1.getPrisonName().compareTo(o2.getPrisonName()) != 0) {
					return 1;
				}
				if (o1.getPrisonName() == o2.getPrisonName()) {
					return 0;
				}
				return -1;
			}
		});
		String curPName="";
		if(dataset.size()>0){
			dataset.get(0).getPrisonName();
		}
		int xIndex=1;
		
		for(int i=0;i<dataset.size();i++){
			ExportRsRj cur=dataset.get(i);
			if(!curPName.equals(cur.getPrisonName())){
				curPName=cur.getPrisonName();
				xIndex=1;
			}
			
			cur.setId(xIndex);
			xIndex++;
		}
		
		String[] headers = { "监区", "序号", "信息内容", "处置措施", "完成情况", "科室点评" };
		Integer[] headersL={8,8,28,28,28,28};	
		ExportExcel<ExportRsRj> ex = new ExportExcel<ExportRsRj>();
//		Date curD = new Date();
//		SimpleDateFormat dFormat = new SimpleDateFormat("yyyy年MM月dd日");
//		String dStr = dFormat.format(curD);
		String note = " 单位：重庆市渝西监狱  日期：" + startTime+"~"+endTime;
		try {
			new ExportExcelUtil<ExportRsRj>().ExportExcelRsRj(ex, dataset, "渝西大监狱日搜日解导出表", headers,headersL, "渝西大监狱日搜日解导出表",
					note, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public String getCurUserB(HttpSession session) {
		try {
			UserInfo u = userService.getCurLoginUser(session);
			UserInfo uB = userService.getUserBByUserA(u);
			Obj obj = new Obj(true, "获取B角成功", uB, System.currentTimeMillis(), null, "获取B角");
			return gson.toJson(obj);
		} catch (Exception e) {
			Obj obj = new Obj(false, "获取B角失败", null, System.currentTimeMillis(), "10001", "获取B角");
			return gson.toJson(obj);
		}
	}

	@Override
	public String modifyUserB(Integer userId, String userName, HttpSession session) {
		UserInfo userA = userService.getCurLoginUser(session);
		UserInfo userB = new UserInfo();
		userB.setUserId(userId);
		userB.setUserName(userName);

		if (userService.upDateMapATOB(userA, userB)) {
			Msg msg = new Msg(true, "操作成功", System.currentTimeMillis(), null, "修改获取添加B角");
			return gson.toJson(msg);
		} else {
			Msg msg = new Msg(false, "操作失败", System.currentTimeMillis(), "10001", "修改获取添加B角");
			return gson.toJson(msg);
		}

	}

	@Override
	public void ExportTaskReseachWord(Integer[] idArray, String address, String time, String people, HttpSession session,
			HttpServletResponse response,HttpServletRequest request) {
		try{
			Map dataMap = new HashMap<>();
			UserPowerView u = userService.curLoginUserPowerView(session);
			String pName=u.getMaxStructure().getName();
			dataMap.put("prison",pName);
			dataMap.put("userName", time);
			dataMap.put("address", address);
			dataMap.put("pNames", people);	
			
			List<TaskReseachWord> data = excelDao.getTaskReseach(idArray);	
			
			List<TaskReseachWord> st1 = new ArrayList<TaskReseachWord>();
			List<TaskReseachWord> st2 = new ArrayList<TaskReseachWord>();
			List<TaskReseachWord> st3 = new ArrayList<TaskReseachWord>();
			
			Iterator<TaskReseachWord> it=data.iterator();
			while(it.hasNext()){
				TaskReseachWord cur=it.next();
				System.out.println(cur);
				Pattern pattern = Pattern.compile(".*情况通报类.*");
				Matcher matcher = pattern.matcher(cur.getSouce());
				boolean b= matcher.matches();
				if(b){
					st1.add(cur);
					continue;
				}
				
				Pattern pattern2 = Pattern.compile(".*显性（即时）任务派遣类.*");
				Matcher matcher2 = pattern2.matcher(cur.getSouce());
				boolean b2= matcher2.matches();
				if(b2){
					st2.add(cur);
					continue;
				}
				
				Pattern pattern1 = Pattern.compile(".*需分析研判.*");
				Matcher matcher1 = pattern1.matcher(cur.getSouce());
				boolean b1= matcher1.matches();
				if(b1){
					st3.add(cur);
					continue;
				}
			}
			
			
			
			
			
			
			
			List<InformationPort> portDataSource=informationPortDao.getAllInfoPort();
			
			List<TaskContainer> rst1=getSortList(st1,portDataSource);
			List<TaskContainer> rst2=getSortList(st2,portDataSource);
			List<TaskContainer> rst3=getSortList(st3,portDataSource);
			
			dataMap.put("table1", rst1);
			dataMap.put("table2", rst2);
			dataMap.put("table3", rst3);
			ExportTaskWord exWord=new ExportTaskWord();
			exWord.importExcel(dataMap, pName+"监区大安全信息分析研判会议记录", request, response);
		}catch(Exception e){
			e.printStackTrace();
		}
		

	}
	
	private List<TaskContainer> getSortList(List<TaskReseachWord> datas,List<InformationPort> pData){
		List<InformationPort> one=getOneList(pData);
		List<Map<String,Object>> rsList=new ArrayList<Map<String, Object>>();
		
		for (Iterator iterator = one.iterator(); iterator.hasNext();) {
			InformationPort informationPort = (InformationPort) iterator.next();
			List<InformationPort> cp=findChild(informationPort, pData);
			cp.add(informationPort);
			Map<String, Object> item=new HashMap<String, Object>();
			item.put("name", informationPort.getPortName());
			item.put("list",cp);
			rsList.add(item);
		}
		
		List<TaskContainer> sortRsList=new ArrayList<TaskContainer>();
		
		
		for (Iterator iterator = datas.iterator(); iterator.hasNext();) {
			TaskReseachWord cur = (TaskReseachWord) iterator.next();
			String name=check(cur.getPort(),rsList);
			sortRsList=addOneToList(name,cur,sortRsList);
		}
		
		return sortRsList;		
	}
	
	private List<TaskContainer> addOneToList(String name,TaskReseachWord item,List<TaskContainer> rs){
		boolean isDo=false;
		for(int i=0;i<rs.size();i++){
			TaskContainer cur=rs.get(i);
			if(cur.getPortName().endsWith(name)){
				List<TaskReseachWord> curlist=cur.getList();
				curlist.add(item);
				cur.setList(curlist);
				isDo=true;
				break;
			}
		}
		if(!isDo){
			List<TaskReseachWord> list=new ArrayList<TaskReseachWord>();
			list.add(item);
			TaskContainer e=new TaskContainer(name, list);
			rs.add(e);
		}
		return rs;		
	}
	private String check(Integer pId,List<Map<String,Object>>  rs){
		for (Iterator iterator = rs.iterator(); iterator.hasNext();) {
			Map<String, Object> map = (Map<String, Object>) iterator.next();
			List<InformationPort> data=(List<InformationPort>) map.get("list");
			if(checkIsIn(pId, data)){
				return map.get("name").toString();
			}			
		}
		return null;		
	}
	private List<InformationPort> getOneList(List<InformationPort> pData){
		
		List<InformationPort> rs= new ArrayList<InformationPort>();
		for (Iterator iterator = pData.iterator(); iterator.hasNext();) {
			InformationPort informationPort = (InformationPort) iterator.next();
			if(informationPort.getSuperId()==0){
				rs.add(informationPort);
			}			
		}		
		return rs;		
	}
	
	private  List<InformationPort> findChild(InformationPort x,List<InformationPort> source){
		
		List<InformationPort> rs=new ArrayList<InformationPort>();
		
		Integer portId=x.getId();
		Iterator<InformationPort> it=source.iterator();
		while(it.hasNext()){
			InformationPort cur=it.next();
			if(cur.getSuperId()==portId){
				rs.add(cur);
				rs.addAll(findChild(cur,source));
			}
		}
		return rs;
	}
	
	private  boolean checkIsIn(Integer itemId,List<InformationPort> data){
		
		for (Iterator iterator = data.iterator(); iterator.hasNext();) {
			InformationPort informationPort = (InformationPort) iterator.next();
			if(informationPort.getId()==itemId){
				return true;
			}
		}
		
		return false;
	}


	@Override
	public void ExportUserCustomExcel(Integer[] idArray, String[] title, String tablename,
			HttpServletRequest request, HttpServletResponse reponse) {		
		List<String> filds=new ArrayList<String>();
		List<String> herders=new ArrayList<String>();
		List<Integer> headerL=new ArrayList<Integer>();
	
		try{
			for(String oneStr:title){			
				oneStr=oneStr.replaceAll("\\\\'", "'");			
				UserCustomRequest cur=gson.fromJson(oneStr, UserCustomRequest.class);			
				herders.add(cur.getName());
				filds.add(cur.getFild());
				String fName=cur.getName().trim();
				if(fName.equals("信息内容")||fName.equals("信息简介")||fName.equals("完成情况")){
					headerL.add(24);
				}else{
					if(fName.equals("流程处理表")||fName.equals("点评记录")){
						headerL.add(24*3);
					}else{
						headerL.add(12);
					}
				}
				
				
			}		
		}catch(Exception e){
			if(title==null){
				return ;
			}
			if(title.length==2){
				String oneStr=title[0]+","+title[1];			
				oneStr=oneStr.replaceAll("\\\\'", "'");					
				UserCustomRequest cur=gson.fromJson(oneStr, UserCustomRequest.class);			
				herders.add(cur.getName());
				filds.add(cur.getFild());
				String fName=cur.getName().trim();
				if(fName.equals("信息内容")||fName.equals("信息简介")||fName.equals("完成情况")){
					headerL.add(24);
				}else{
					if(fName.equals("流程处理表")||fName.equals("点评记录")){
						headerL.add(24*3);
					}else{
						headerL.add(12);
					}
					
				}
			}
		}
		try{
			List<UserCustom> dataset=new ArrayList<UserCustom>();
			dataset=excelDao.getInforList(idArray);
			dataset=filter(dataset);
			com.yuxi.Util.ExportUserCustomExcel<UserCustom> ex=new com.yuxi.Util.ExportUserCustomExcel<UserCustom>();
			new ExportUserCustomServlet<UserCustom>().importExcel(ex, dataset,headerL.toArray(new Integer[headerL.size()]), filds.toArray(new String[filds.size()]), herders.toArray(new String[herders.size()]), tablename, request, reponse);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	 
	private List<UserCustom> filter(List<UserCustom> dataset) {
		//System.out.println("123123");
		Integer iIndex=1;
		for (Iterator iterator = dataset.iterator(); iterator.hasNext();) {
			UserCustom clss = (UserCustom) iterator.next();
			clss.setId(Integer.toString(iIndex));
			iIndex++;
			Integer id=Integer.parseInt(clss.getId());
			List<InformationFlow> fs=informationFlowService.getInformationFlowByInfoId(id);
			StringBuffer Fd=new StringBuffer();
			if(fs!=null){
				for (InformationFlow informationFlow : fs) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					String date = sdf.format(new Date(informationFlow.getCreateTime()));				
					Fd.append("操作人：").append(informationFlow.getUserName())
					.append(" 时间：").append(date)
					.append(" 操作：").append(informationFlow.getOperation())
					.append(" 备注：").append(informationFlow.getRemark())
					.append(" 流程：").append(ConfigStatic.FLOWTABLEID.get(Integer.toString(informationFlow.getFlowId())))
					.append(" \n\r");			
				}
			}
			StringBuffer commentdo=new StringBuffer("");
			CommentRecord c=prisonService.getCommentRecordByInfoId(id);
			if(c!=null){				
				commentdo.append("信息录入和收集质量:").append(c.getInformationQualityName())
				.append("录入和收集点评:").append(c.getContent())
				.append("任务完成情况:").append(c.getTaskCompletionName())
				.append("完成情况点评:").append(c.getCompleteContent())
				.append("点评人:").append(c.getUserName());	
			}
			clss.setFlowDo(Fd.toString());
			clss.setCommentdo(commentdo.toString());
			UserInfo u=UserTableStatic.findUserById(Integer.parseInt(clss.getUserId()));
			clss.setUserId( u.getUserName());
			Field[] fields = clss.getClass().getDeclaredFields();
			for (short i = 0; i < fields.length; i++) {
				Field field = fields[i];
				String fieldName = field.getName();
				String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
				String setMethodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
				Class tCls = clss.getClass();
				try {
					Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
					Object value = getMethod.invoke(clss, new Object[] {});
					
					if(value!=null&&!value.toString().isEmpty()){
						value=value.toString().replaceAll("<br>", "").replaceAll("&nbsp", "");
						Method setMethod = tCls.getMethod(setMethodName, new Class[] {String.class});
						//System.out.println(123);
						setMethod.invoke(clss, new Object[] {new String(value.toString())});
					}
				} catch (NoSuchMethodException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SecurityException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
		System.out.println("123123");
		return dataset;
	}

	@Override
	public String ownWordComment(Integer id,String comment,HttpServletRequest request, HttpServletResponse response) {
		if(utilService.ownWordComment(id,comment)){
			Msg msg=new Msg(true, "点评成功", System.currentTimeMillis(), null, "点评民警导出");
			return gson.toJson(msg);
		}else{
			Msg msg=new Msg(false, "点评失败", System.currentTimeMillis(), "10001","点评民警导出");
			return gson.toJson(msg);
		}
		
	}

	@Override
	public String addBorwseRec(Integer id, HttpSession session) {
		try{
			OwnwordRecordBorwser oBorwser=new OwnwordRecordBorwser();
			oBorwser.setRecordId(id);
			UserInfo u=userService.getCurLoginUser(session);
			oBorwser.setCreateTime(System.currentTimeMillis());
			oBorwser.setUserId(u.getUserId());
			oBorwser.setUserName(u.getUserName());
			ownwordRecordBorwserDao.add(oBorwser);		
			Msg msg=new Msg(true, "添加成功", System.currentTimeMillis(), null, "添加一条浏览记录");
			return gson.toJson(msg);
		}catch(Exception e){
			Msg msg=new Msg(false, "添加失败", System.currentTimeMillis(), "10001", "添加一条浏览记录");
			return gson.toJson(msg);
		}
	}

	@Override
	public String getBorecord(Integer id) {
		try{
			List<OwnwordRecordBorwser> rs=ownwordRecordBorwserDao.get(id);
			Obj obj=new Obj(true, "获取浏览记录成功", rs, System.currentTimeMillis(), null, "获取浏览记录");
	 		return gson.toJson(obj);
		}catch(Exception e){
			Obj obj=new Obj(false, "获取浏览记录失败", null, System.currentTimeMillis(), "10001", "获取浏览记录");
	 		return gson.toJson(obj);
		}
	}

	@Override
	public String getWaitShowList(OwnQuery query, Page<OwnWordRecord> p, HttpSession session) {
		UserInfo u=userService.getCurLoginUser(session);
		PageQuerySave<OwnQuery> pageQuerySave=new PageQuerySave<OwnQuery>(query,p.getTotalPage());
		PageQuerySave<OwnQuery> pSession=(PageQuerySave<OwnQuery>)session.getAttribute("ownerQueryPage");
		if(pSession!=null&&pSession.isEable()){
			query=pSession.getQuery();
			p.setCurrentPage(pSession.getPageNum());
		}
		try{
			if(query.getUserAB()!=null&&!query.getUserAB().isEmpty()){
				query.setUserABId(userInfoDao.getUserListByUserAccountOrName(query.getUserAB()).get(0).getUserId());;
			}
		}catch(Exception e){
			query.setUserABId(0);
		}
		String Str=gson.toJson(excelDao.getRecord(query, p, u));
		session.setAttribute("ownerQueryPage", pageQuerySave);
		return Str;
	}

	@Override
	public String getAlreadyShowList(OwnQuery query, Page<OwnWordRecord> p, HttpSession session) {
		UserInfo u=userService.getCurLoginUser(session);
		PageQuerySave<OwnQuery> pageQuerySave=new PageQuerySave<OwnQuery>(query, p.getCurrentPage());
		PageQuerySave<OwnQuery> pageQuerySaveSeesion=(PageQuerySave<OwnQuery>)session.getAttribute("ownerQueryPage");
		if(pageQuerySaveSeesion!=null&&pageQuerySaveSeesion.isEable()){
			query=pageQuerySaveSeesion.getQuery();
			p.setCurrentPage(pageQuerySaveSeesion.getPageNum());
		}
		if(query.getUserAB()!=null&&!query.getUserAB().isEmpty()){
			try{
				query.setUserABId(userInfoDao.getUserListByUserAccountOrName(query.getUserAB()).get(0).getUserId());
			}catch(Exception e){
				query.setUserABId(0);
			}
		}
		String rss= gson.toJson(excelDao.getAlreadyRecord(query, p, u));
		session.setAttribute("ownerQueryPage", pageQuerySave);
		return rss;
	}

	@Override
	public String getVerifyCodeOff() {
		Msg msg=new Msg();
		msg.setStatus(ConfigStatic.VerifyCodeOff);
		return gson.toJson(msg);
	}

	@Override
	public String moDiFyVerifyCodeOff(boolean isOff) {
		ConfigStatic.VerifyCodeOff=isOff;
		return null;
	}

	@Override
	public String userInfoUpQuery(HttpSession session) {
		PageQuerySave<UserQuery> userQueryPagecur=(PageQuerySave<UserQuery>)session.getAttribute("userListQuery");
		userQueryPagecur.setEable(true);
		session.removeAttribute("userListQuery");
		session.setAttribute("userListQuery",userQueryPagecur);
		System.out.println(userQueryPagecur);
		return "";
	}

	@Override
	public String ownerPageQuery(HttpSession session) {
		PageQuerySave<OwnQuery> userQueryPagecur=(PageQuerySave<OwnQuery>)session.getAttribute("ownerQueryPage");
		userQueryPagecur.setEable(true);
		session.removeAttribute("ownerQueryPage");
		session.setAttribute("ownerQueryPage",userQueryPagecur);
		//System.out.println(userQueryPagecur);
		//System.out.println("wq ok");
		return "";
	}

}
